package com.ihd.ihardware.view.scooter.view;

import android.app.Dialog;
import android.arch.lifecycle.Observer;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ihd.ihardware.R;
import com.ihd.ihardware.common.AppConstans;
import com.ihd.ihardware.databinding.ActivityScBindingBinding;
import com.ihd.ihardware.pojo.DeviceListRes;
import com.ihd.ihardware.view.scooter.viewModel.SCBindViewModel;
import com.inuker.bluetooth.library.connect.options.BleConnectOptions;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.List;

import cn.wowjoy.commonlibrary.base.BaseActivity;
import cn.wowjoy.commonlibrary.base.BaseConsumer;
import cn.wowjoy.commonlibrary.utils.BLEUtils;
import cn.wowjoy.commonlibrary.utils.DialogUtils;
import cn.wowjoy.commonlibrary.utils.InputTools;
import cn.wowjoy.commonlibrary.utils.SPUtils;
import cn.wowjoy.commonlibrary.utils.ToastUtils;
import cn.wowjoy.commonlibrary.widget.MDialog;
import cn.wowjoy.commonlibrary.widget.PayPsdInputView;

import static com.ihd.ihardware.common.AppConstans.Lock_Notify_Character_UUID;
import static com.ihd.ihardware.common.AppConstans.Lock_Service_UUID;
import static com.ihd.ihardware.common.AppConstans.Notify_Character_UUID;
import static com.ihd.ihardware.common.AppConstans.Notify_Service_UUID;
import static com.ihd.ihardware.common.AppConstans.Write_Character_UUID;
import static com.ihd.ihardware.common.AppConstans.Write_Service_UUID;
import static com.inuker.bluetooth.library.Constants.REQUEST_SUCCESS;

public class SCBindingActivity extends BaseActivity<ActivityScBindingBinding, SCBindViewModel> {
    private Dialog mCameraDialog;
    private Dialog waitDialog;
    private ItemAdapter mItemAdapter;
    private List<BluetoothDevice> mDevices = new ArrayList<>();
    private MDialog mPswDg;
    private MDialog mErrDg;
    private long t0;
    private boolean isSearching = false;
    private BluetoothDevice mBD;
    private BleConnectOptions options = new BleConnectOptions.Builder()
            .setConnectRetry(3)
            .setConnectTimeout(5000)
            .setServiceDiscoverRetry(3)
            .setServiceDiscoverTimeout(5000)
            .build();
    private DeviceListRes.DataBean.ListBean mLocks = null;

    @Override
    protected void init(Bundle savedInstanceState) {
        mImmersionBar.statusBarDarkFont(false).init();

        binding.mtitlebar.setLeftBack(this);
        binding.mtitlebar.setLeftImageResource(R.drawable.bike_nb_back);

        binding.retry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchNow();
            }
        });

        binding.diffuseView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchNow();
            }
        });

        SearchNow();

        LiveEventBus.get()
                .with("onNotify", String.class)
                .observe(this, new Observer<String>() {
                    @Override
                    public void onChanged(@Nullable String s) {
                        Log.e("LBA onNotify", s);
                        if (s.contains(":")) {
                            mPswDg = DialogUtils.pswDialog(SCBindingActivity.this);
                            mPswDg.OnListClickItem(new MDialog.OnListClickedInterface() {
                                @Override
                                public void OnListClicked(PayPsdInputView ai) {
                                    InputTools.HideKeyboard(ai);
                                    mPswDg.cancel();
                                    BLEUtils.writePsw(s, "A50a010" + ai.getPasswordString().substring(0, 1) + "0" + ai.getPasswordString().substring(1, 2) + "0" + ai.getPasswordString().substring(2, 3) + "0" + ai.getPasswordString().substring(3, 4) + "0000", "", Write_Service_UUID, Write_Character_UUID);
                                }
                            });
                        } else {
                            if (s.startsWith("5A0501")) {
                                if (s.startsWith("5A050101")) {
                                    viewModel.bind(mBD.getAddress());
                                } else {
                                    mPswDg.cancel();
                                    ToastUtils.showShort(SCBindingActivity.this, "密码错误，请重新输入");
                                    mPswDg = DialogUtils.pswDialog(SCBindingActivity.this);
                                    mPswDg.OnListClickItem(new MDialog.OnListClickedInterface() {
                                        @Override
                                        public void OnListClicked(PayPsdInputView ai) {
                                            InputTools.HideKeyboard(ai);
                                            mPswDg.cancel();
                                            BLEUtils.writePsw(s, "A50a010" + ai.getPasswordString().substring(0, 1) + "0" + ai.getPasswordString().substring(1, 2) + "0" + ai.getPasswordString().substring(2, 3) + "0" + ai.getPasswordString().substring(3, 4) + "0000", "", Write_Service_UUID, Write_Character_UUID);
                                        }
                                    });
                                }
                            }
                        }
                    }
                });

        setRx(AppConstans.BIND, new BaseConsumer<DeviceListRes>() {
            @Override
            protected void onStart() {
            }

            @Override
            protected void onSuccess(DeviceListRes mLiveData) {
                DialogUtils.successDialog(SCBindingActivity.this, MDialog.DG_TYPE.SUCCESS, R.drawable.toasticon_suc, "绑定成功");
                SPUtils.putString(AppConstans.DEVICES, new Gson().toJson(mLiveData.getData().getList(), new TypeToken<List<DeviceListRes.DataBean.ListBean>>() {
                }.getType()));

                for (DeviceListRes.DataBean.ListBean ddl : mLiveData.getData().getList()) {
                    if ("4".equals(ddl.getType()))
                        mLocks = ddl;
                }
                BLEUtils.closeNotify(mBD.getAddress(), Notify_Service_UUID, Notify_Character_UUID);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent mIntent = new Intent(SCBindingActivity.this, SCActivity.class);
                        mIntent.putExtra("sc", mLocks);
                        startActivity(mIntent);
                        finish();
                    }
                }, 2100);
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(SCBindingActivity.this, error.getMessage());
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sc_binding;
    }

    @Override
    protected Class getViewModelClass() {
        return SCBindViewModel.class;
    }

    private void showDg(BluetoothDevice bd) {
        if (mCameraDialog == null || !mCameraDialog.isShowing()) {
            mDevices.clear();
            if (!mDevices.contains(bd))
                mDevices.add(bd);
            mCameraDialog = new Dialog(this, R.style.dialog_no_bg);
            LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.pop_bottom, null);
            root.findViewById(R.id.popBG).setBackgroundResource(R.drawable.corners_292b3d);
            RecyclerView mRV = (RecyclerView) root.findViewById(R.id.scooters);
            mRV.setLayoutManager(new LinearLayoutManager(this));
            mItemAdapter = new ItemAdapter(mDevices);
            mRV.setAdapter(mItemAdapter);
            mCameraDialog.setContentView(root);
            mCameraDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    BLEUtils.getInstance().stopSearch();
                }
            });
            Window dialogWindow = mCameraDialog.getWindow();
            dialogWindow.setGravity(Gravity.BOTTOM);
            dialogWindow.setWindowAnimations(R.style.popupAnimation);
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = (int) getResources().getDisplayMetrics().widthPixels;
            root.measure(0, 0);
            lp.height = root.getMeasuredHeight();
            dialogWindow.setAttributes(lp);
            mCameraDialog.show();
        } else {
            if (!mDevices.contains(bd))
                mDevices.add(bd);
            mItemAdapter.notifyDataSetChanged();
        }
    }

    public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.MyViewHolder> {
        private List<BluetoothDevice> mDevices;

        public ItemAdapter(List<BluetoothDevice> datas) {
            mDevices = datas;
        }

        @Override
        public ItemAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_device, parent, false);
            return new ItemAdapter.MyViewHolder(layout);
        }

        @Override
        public void onBindViewHolder(final ItemAdapter.MyViewHolder holder, final int position) {
            holder.mIcon.setImageResource(R.drawable.bike_sblist);
            holder.mConn.setBackgroundResource(R.drawable.corners_line_10b1fe);
            holder.mConnTV.setTextColor(getResources().getColor(R.color.C_10B1FE));
            holder.mDivide.setBackgroundColor(getResources().getColor(R.color.C_3F4151));

            if (TextUtils.isEmpty(mDevices.get(position).getName()))
                holder.drugItem.setText(mDevices.get(position).getAddress());
            else
                holder.drugItem.setText(mDevices.get(position).getName());
            holder.mConn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    waitDialog = DialogUtils.waitingDialog(SCBindingActivity.this);
                    BLEUtils.getInstance().stopSearch();
                    holder.mConnTV.setText(getString(R.string.connting));
                    holder.mConnTV.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);

                    BLEUtils.getInstance().connect(mDevices.get(position).getAddress(), options, new BleConnectResponse() {
                        @Override
                        public void onResponse(int code, BleGattProfile data) {
                            if (code == REQUEST_SUCCESS) {
                                mBD = mDevices.get(position);
                                BLEUtils.openNotify(mBD.getAddress(), Notify_Service_UUID, Notify_Character_UUID);
                                mCameraDialog.cancel();
                            } else {
                                ToastUtils.showLong(SCBindingActivity.this, getString(R.string.conn_fail));
                                holder.mConnTV.setText(getString(R.string.conn));
                                holder.mConnTV.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
                                BLEUtils.getInstance().disconnect(mDevices.get(position).getAddress());
                            }
                            DialogUtils.dismiss(SCBindingActivity.this);
                        }
                    });
                }
            });
            holder.itemView.setTag(position);
        }

        @Override
        public int getItemCount() {
            return mDevices.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            private TextView drugItem;
            private RelativeLayout mConn;
            private TextView mConnTV;
            private ImageView mIcon;
            private View mDivide;

            public MyViewHolder(View view) {
                super(view);
                mIcon = (ImageView) view.findViewById(R.id.icon);
                drugItem = (TextView) view.findViewById(R.id.d_name);
                mConn = (RelativeLayout) view.findViewById(R.id.search);
                mConnTV = (TextView) view.findViewById(R.id.conn);
                mDivide = view.findViewById(R.id.divide);
            }
        }

    }

    private void SearchNow() {
        binding.diffuseView.setVisibility(View.VISIBLE);
        binding.nobg.setVisibility(View.GONE);
        binding.hint0.setVisibility(View.GONE);
        binding.retry.setVisibility(View.GONE);
        binding.searchHint.setText("正在搜索");
        binding.hint.setText("请让手机靠近滑板车");
        binding.diffuseView.setCoreImage(R.drawable.bike_searching);
        mDevices.clear();
        binding.diffuseView.start();
        BLEUtils.getInstance().search(new SearchRequest.Builder().searchBluetoothLeDevice(5000).build(), new SearchResponse() {
            @Override
            public void onSearchStarted() {
                isSearching = true;
            }

            @Override
            public void onDeviceFounded(SearchResult device) {
                binding.searchHint.setText("已搜到滑板车");
                binding.hint.setText("点击连接即可");
                binding.diffuseView.setCoreImage(R.drawable.bike_searched);
                showDg(device.device);
                mCameraDialog.setCanceledOnTouchOutside(false);
            }

            @Override
            public void onSearchStopped() {
                if (mCameraDialog != null)
                    mCameraDialog.setCanceledOnTouchOutside(true);
                isSearching = false;
                binding.diffuseView.stop();
                BLEUtils.getInstance().stopSearch();
                if (mDevices.size() == 0) {
                    binding.hint0.setVisibility(View.VISIBLE);
                    binding.nobg.setVisibility(View.VISIBLE);
                    binding.retry.setVisibility(View.VISIBLE);
                    binding.searchHint.setText("未发现设备");
                    binding.hint.setText("");
                    binding.diffuseView.cancel();
                    binding.diffuseView.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onSearchCanceled() {
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mBD != null && !TextUtils.isEmpty(mBD.getAddress()))
                BLEUtils.closeNotify(mBD.getAddress(), Lock_Service_UUID, Lock_Notify_Character_UUID);
        }
        return super.onKeyDown(keyCode, event);
    }

}
